package com.conversationboard.api;

import java.io.IOException;
import java.sql.SQLException;

import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.core.SecurityContext;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathExpressionException;

import org.w3c.dom.Document;
import org.xml.sax.SAXException;

import com.conversationboard.api.security.Security;
import com.conversationboard.api.xml.ApiXPath;
import com.conversationboard.api.xml.XmlUtils;
import com.conversationboard.cache.VoterCache;
import com.conversationboard.model.User;

public class VoteProcessor implements Processor {

	/* Input Form: <Vote><LoginId>...</LoginId><BoardId>...</BoardId><ThreadId>...</ThreadId>
	 * <OptionId>...</OptionId></Vote> */

	private static XPathExpression boardIdExpression;
	private static XPathExpression threadIdExpression;
	private static XPathExpression optionIdExpression;

	static {
		try {
			boardIdExpression = ApiXPath.getXPath().compile("/Requests/Vote/BoardId/text()");
			threadIdExpression = ApiXPath.getXPath().compile("/Requests/Vote/ThreadId/text()");
			optionIdExpression = ApiXPath.getXPath().compile("/Requests/Vote/OptionId/text()");
		} catch (XPathExpressionException e) {
		}
	}


	@Override
	public String processXml(String xml, SecurityContext securityContext, HttpServletRequest request) throws ApiException {

		if (!Security.isLoggedIn(securityContext)) {
			return "<Vote><Error>You need to be logged in to vote</Error></Vote>";
		}

		User user = null;

		try {
			user = User.get(request.getUserPrincipal());

			Document document = XmlUtils.getDocument(xml);

			int boardId = Integer.parseInt((String) boardIdExpression.evaluate(document, XPathConstants.STRING));
			int threadId = Integer.parseInt((String) threadIdExpression.evaluate(document, XPathConstants.STRING));
			int optionId = Integer.parseInt((String) optionIdExpression.evaluate(document, XPathConstants.STRING));

			VoterCache.addVote(user.getLoginId(), boardId, threadId, optionId);
			
			return "<Vote><Success>Yes</Success></Vote>";
			
		} catch (SQLException e) {
			throw new ApiException(e);
		} catch (ParserConfigurationException e) {
			throw new ApiException(e);
		} catch (IOException e) {
			throw new ApiException(e);
		} catch (SAXException e) {
			throw new ApiException(e);
		} catch (NumberFormatException e) {
			throw new ApiException(e);
		} catch (XPathExpressionException e) {
			throw new ApiException(e);
		}

	}

}
